//
//  SearchDingdanViewController.m
//  LoveAttention
//
//  Created by 鞠超 on 16/3/11.
//  Copyright © 2016年 JC. All rights reserved.
//

#import "SearchDingdanViewController.h"

#import "Dingdan_Model.h"
#import "DingdanList_Model.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "DataProvider.h"
#import "SVProgressHUD.h"
#import "DingdanDetailViewController.h"
@interface SearchDingdanViewController ()  <UITableViewDelegate, UITableViewDataSource , UITextFieldDelegate>

@property (nonatomic, strong) UITableView * tableView;

@property (nonatomic, strong) UITextField * text_search;


//数据
@property (nonatomic, strong) NSMutableArray * arr_all;

@property (nonatomic, strong) NSMutableArray * arr_list;



@end

@implementation SearchDingdanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self p_navigationController];
    
    [self p_setupView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - navigationController
- (void)p_navigationController
{
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    self.navigationItem.title = @"订单搜索";
    UIButton * btn = [UIButton buttonWithType:(UIButtonTypeSystem)];
    [btn setBackgroundImage:[UIImage imageNamed:@"返回"] forState:(UIControlStateNormal)];
    btn.frame = CGRectMake(10, 20, 18, 22);
    [btn addTarget:self action:@selector(leftBarButtonItemAction:) forControlEvents:(UIControlEventTouchUpInside)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
}

//点击事件(左)
- (void)leftBarButtonItemAction:(UIBarButtonItem *)bar
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 布局

- (void)p_setupView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:(UITableViewStylePlain)];
    
    self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    UIView * view_search = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];
    view_search.backgroundColor = [UIColor whiteColor];
    
    UIImageView * image_search = [[UIImageView alloc] initWithFrame:CGRectMake(15, 10, 30, 30)];
    image_search.image = [UIImage imageNamed:@"iconfont-sousuo"];
    [view_search addSubview:image_search];
    
    self.text_search = [[UITextField alloc] init];
    
    self.text_search.returnKeyType = UIReturnKeyDone;
    self.text_search.frame = CGRectMake(CGRectGetMaxX(image_search.frame) + 10, 7, self.view.frame.size.width - CGRectGetMaxX(image_search.frame) - 70, 36);
    UIView * view_w = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 2)];
    self.text_search.leftView = view_w;
    self.text_search.leftViewMode = UITextFieldViewModeAlways;
    self.text_search.layer.cornerRadius = 5;
    self.text_search.layer.borderColor = [UIColor grayColor].CGColor;
    self.text_search.layer.borderWidth = 1;
    self.text_search.keyboardType = UIKeyboardTypeNumberPad;
    self.text_search.clearButtonMode = UITextFieldViewModeAlways;
    //    self.text_search.layer.cornerRadius = 5;
    //    self.text_search.layer.borderColor = [UIColor groupTableViewBackgroundColor].CGColor;
    //    self.text_search.layer.borderWidth = 1;
    self.text_search.delegate = self;
    [view_search addSubview:self.text_search];
    
    UIButton * btn_search = [UIButton buttonWithType:(UIButtonTypeSystem)];
    btn_search.frame = CGRectMake(CGRectGetMaxX(self.text_search.frame) + 5, 10, 50, 30);
//    [btn_search setBackgroundImage:[UIImage imageNamed:@"iconfont-quxiao"] forState:(UIControlStateNormal)];
    [btn_search setTitle:@"搜索" forState:(UIControlStateNormal)];
    [btn_search setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    [view_search addSubview:btn_search];
    [btn_search addTarget:self action:@selector(btn_searchAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    self.tableView.tableHeaderView = view_search;

    
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    [self.view addSubview:self.tableView];
}

#pragma mark - 数据
- (NSInteger )numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.arr_all.count;
}

- (NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3 + [self.arr_list[section] count];
}

- (CGFloat )tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger number = [self.arr_list[indexPath.section] count];
    
    if(indexPath.row == 0 || indexPath.row == number + 1 || indexPath.row == number+ 2)
    {
        return 40;
    }
    else
    {
        return 100;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * cell = [[UITableViewCell alloc] init];
    
    NSInteger number = [self.arr_list[indexPath.section] count];
    
    if(indexPath.row == 0)
    {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        UILabel * name = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, SCREEN_WIDTH / 2 + 50, 30)];
        name.text = @"订单号";
        
        [cell addSubview:name];
        
        UILabel * type = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(name.frame) + 5, 5, SCREEN_WIDTH - CGRectGetMaxX(name.frame) - 10, 30)];
        type.text = @"未付款";
        type.textColor = [UIColor orangeColor];
        type.textAlignment = NSTextAlignmentRight;
        [cell addSubview:type];
        
        if(self.arr_all.count != 0)
        {
            Dingdan_Model * model = self.arr_all[indexPath.section];
            
            name.text = model.ordernum;
            
            if([model.type integerValue] == 0)
            {
                switch ([model.state integerValue])
                {
                    case 0:
                    {
                        type.text = @"未付款";
                    }
                        break;
                    case 1:
                    {
                        type.text = @"未消费";
                    }
                        break;
                    case 2:
                    {
                        type.text = @"已完成";
                    }
                        break;
                    default:
                        break;
                }
            }
            else
            {
                switch ([model.state integerValue])
                {
                    case 0:
                    {
                        type.text = @"未付款";
                    }
                        break;
                    case 1:
                    {
                        type.text = @"已付款";
                    }
                        break;
                    case 2:
                    {
                        type.text = @"已收货";
                    }
                        break;
                    default:
                        break;
                }
            }
        }
    }
    else if(indexPath.row == number + 1)
    {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        UILabel * money = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 130, 5, 120, 30)];
        money.text = @"共付 ¥ 100.00";
        money.font = [UIFont systemFontOfSize:15];
        money.textAlignment = NSTextAlignmentRight;
        [cell addSubview:money];
        
        //        UILabel * num = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 150 - 130, 5, 150, 30)];
        //        num.text = @"共计2件商品";
        //        num.font = [UIFont systemFontOfSize:15];
        //        num.textAlignment = NSTextAlignmentRight;
        //        [cell addSubview:num];
        
        if(self.arr_all.count != 0)
        {
            Dingdan_Model * model = self.arr_all[indexPath.section];
            
            money.text = [NSString stringWithFormat:@"共付 ¥ %@",model.price];
            
            //            num.text = [NSString stringWithFormat:@"共计%ld件商品",[self.arr_list[indexPath.section] count]];
        }
    }
    else if (indexPath.row == number + 2)
    {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        UIButton * btn = [UIButton buttonWithType:(UIButtonTypeSystem)];
        btn.frame = CGRectMake(SCREEN_WIDTH - 90, 5, 80, 30);
        btn.tag = 10000 + indexPath.section;
        btn.backgroundColor = [UIColor orangeColor];
        [btn setTitle:@"订单" forState:(UIControlStateNormal)];
        [btn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        
        [btn addTarget:self action:@selector(btnActionDingdan:) forControlEvents:(UIControlEventTouchUpInside)];
        
        [cell addSubview:btn];
        
        if(self.arr_all.count != 0)
        {
            Dingdan_Model * model = self.arr_all[indexPath.section];
            
            if([model.type integerValue] == 0)
            {
                switch ([model.state integerValue])
                {
                    case 0:
                    {
                        [btn setTitle:@"取消订单" forState:(UIControlStateNormal)];
                        
                    }
                        break;
                    case 1:
                    {
                        [btn setTitle:@"接单" forState:(UIControlStateNormal)];
                        
                    }
                        break;
                    case 2:
                    {
                        [btn setTitle:@"待评价" forState:(UIControlStateNormal)];
                        btn.hidden = YES;
                        
                    }
                        break;
                    default:
                        break;
                }
            }
            else
            {
                switch ([model.state integerValue])
                {
                    case 0:
                    {
                        [btn setTitle:@"取消订单" forState:(UIControlStateNormal)];
                        
                    }
                        break;
                    case 1:
                    {
                        [btn setTitle:@"发货" forState:(UIControlStateNormal)];
                    }
                        break;
                    case 2:
                    {
                        [btn setTitle:@"删除订单" forState:(UIControlStateNormal)];
                    }
                        break;
                    default:
                        break;
                }
            }
            
        }
    }
    else
    {
        UIImageView * image = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 80, 80)];
        image.image = [UIImage imageNamed:@"1136-1"];
        [cell addSubview:image];
        
        UILabel * name = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(image.frame) + 10, 10, SCREEN_WIDTH - CGRectGetMaxX(image.frame) - 10 - 70, 30)];
        name.text = @"哈哈哈哈哈哈哈哈哈哈哈哈";
        name.font = [UIFont systemFontOfSize:15];
        [cell addSubview:name];
        
        UILabel * price = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(name.frame) + 5, 10, 55, 30)];
        price.text = @"￥200.00";
        price.textAlignment = NSTextAlignmentRight;
        price.font = [UIFont systemFontOfSize:13];
        [cell addSubview:price];
        
        UILabel * num = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(name.frame) + 5, CGRectGetMaxY(price.frame), 55, 30)];
        num.text = @"x2";
        num.textAlignment = NSTextAlignmentRight;
        num.font = [UIFont systemFontOfSize:13];
        num.textColor = [UIColor grayColor];
        [cell addSubview:num];
        
        if(self.arr_all.count != 0)
        {
            DingdanList_Model * model = self.arr_list[indexPath.section][indexPath.row - 1];
            NSString *url = [NSString stringWithFormat:@"%@upload/%@",Url,model.imgpath];
            [image sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"1136-1"]];
            
            name.text = model.goodsName;
            
            price.text = [NSString stringWithFormat:@"￥ %@",model.price];
            
            num.text = [NSString stringWithFormat:@"x%@",model.quantity];
        }
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSInteger number = [self.arr_list[indexPath.section] count];
    
    if(indexPath.row == 0 || indexPath.row == number + 1 || indexPath.row == number+ 2)
    {
        
    }
    else
    {
        Dingdan_Model * model = self.arr_all[indexPath.section];
        
        DingdanDetailViewController * dingdanDetailViewController = [[DingdanDetailViewController alloc] init];
        
        dingdanDetailViewController.orderid = model.orderid;
        
        [self showViewController:dingdanDetailViewController sender:nil];
    }

}

#pragma mark - textFiled;
- (void)btn_searchAction:(UIButton *)sender
{
    [self.text_search resignFirstResponder];
    
    if([self.text_search.text length] == 0)
    {
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"搜索内容不能为空" preferredStyle:(UIAlertControllerStyleAlert)];
        
        [self presentViewController:alert animated:YES completion:^{
            
        }];
        
        UIAlertAction * action = [UIAlertAction actionWithTitle:@"知道了" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alert addAction:action];
    }
    else
    {
        DataProvider * dataprovider = [[DataProvider alloc] init];
        NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
        
        [dataprovider setDelegateObject:self setBackFunctionName:@"orderlist:"];
        
        [dataprovider orderlistWith:[defaults objectForKey:@"merchantid"] andpagenumber:@"1" andpagesize:@"10000" andordernum:self.text_search.text];
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.text_search resignFirstResponder];
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.text_search resignFirstResponder];
    
    if([textField.text length] == 0)
    {
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"搜索内容不能为空" preferredStyle:(UIAlertControllerStyleAlert)];
        
        [self presentViewController:alert animated:YES completion:^{
            
        }];
        
        UIAlertAction * action = [UIAlertAction actionWithTitle:@"知道了" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alert addAction:action];
    }
    else
    {
        DataProvider * dataprovider = [[DataProvider alloc] init];
        NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
        
        [dataprovider setDelegateObject:self setBackFunctionName:@"orderlist:"];
        
        [dataprovider orderlistWith:[defaults objectForKey:@"merchantid"] andpagenumber:@"1" andpagesize:@"10000" andordernum:self.text_search.text];
    }
    return YES;
}
#pragma mark - 数据
- (void)orderlist:(id )dict
{
    NSLog(@"%@",dict);
    
    self.arr_all = nil;
    self.arr_list = nil;
    
    if ([dict[@"status"][@"succeed"] intValue] == 1) {
        @try
        {
            for (NSDictionary * dic in dict[@"data"])
            {
                Dingdan_Model * model = [[Dingdan_Model alloc] init];
                
                [model setValuesForKeysWithDictionary:dic];
                
                [self.arr_all addObject:model];
                
                NSMutableArray * arr= [NSMutableArray array];
                
                for (NSDictionary * dict_list in dic[@"goodlist"])
                {
                    DingdanList_Model * model = [[DingdanList_Model alloc] init];
                    
                    [model setValuesForKeysWithDictionary:dict_list];
                    
                    [arr addObject:model];
                }
                
                [self.arr_list addObject:arr];
            }
        }
        @catch (NSException *exception) {
            
        }
        @finally {
            
            Dingdan_Model * model = self.arr_all.firstObject;
            
            if([model.ordernum length] == 0)
            {
                [SVProgressHUD showErrorWithStatus:@"搜索失败" maskType:(SVProgressHUDMaskTypeBlack)];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                //刷新tableView(记住,要更新放在主线程中)
                
                [self.tableView reloadData];
            });
        }
    }
    else
    {
        [SVProgressHUD showErrorWithStatus:dict[@"status"][@"errdesc"] maskType:SVProgressHUDMaskTypeBlack];
    }
}



#pragma mark - 点击事件
- (void )btnActionDingdan:(UIButton *)sender
{
    NSInteger index = sender.tag - 10000;
    NSLog(@"%ld",(long)index);
}


#pragma mark - 懒加载
- (NSMutableArray *)arr_all
{
    if(_arr_all == nil)
    {
        self.arr_all = [NSMutableArray array];
    }
    
    return _arr_all;
}

- (NSMutableArray *)arr_list
{
    if(_arr_list == nil)
    {
        self.arr_list = [NSMutableArray array];
    }
    
    return _arr_list;
}




@end
